package top.fkxuexi.blogapi.core.config.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import top.fkxuexi.blogapi.modules.auth.entity.SysUser;
import top.fkxuexi.blogapi.modules.auth.service.SysRoleService;
import top.fkxuexi.blogapi.modules.auth.service.SysUserService;

import java.util.List;

public class AdminShiroRealm extends AuthorizingRealm {

    /**
     * 参考：https://github.com/cckevincyh/CIYOU/blob/master/src/main/java/com/ciyou/edu/config/shiro/admin/AdminShiroRealm.groovy
     */


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 这个是用户的授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        Integer userId = (Integer) SecurityUtils.getSubject().getPrincipal();
        List<String> permissionList = sysRoleService.getRolePermissionByUserId(userId);
        List<String> roleList = sysRoleService.getRoleNameListByUserId(userId);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 这个是用户的角色，目前是没有什么用的，先放在这里
        authorizationInfo.addRoles(roleList);
        // 这个是用户用户所拥有的菜单，作为用户的权限
        authorizationInfo.addStringPermissions(permissionList);
        return authorizationInfo;
    }

    /**
     * 这个是身份认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        ShiroToken shiroToken = (ShiroToken) token;
        SysUser user = sysUserService.getUserByLoginName(shiroToken.getUsername());
        if (user == null) {
            throw new UnknownAccountException("用户不存在！");
        }
        /**
         *  这里的第一个参数，是可以通过 SecurityUtils.getSubject().getPrincipal() 获取到的
         *
         *  这个地方会进行密码的比对
         */
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getId(),
                user.getPwd(),
                getName()
        );
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        return authenticationInfo;
    }
}
